<template>
  <div class="whitelist-container">
    <h2>白名单用户管理</h2>
    <table class="user-table">
      <thead>
        <tr>
          <th>用户名</th>
          <th>微信 ID</th>
          <th>是否白名单</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.username }}</td>
          <td>{{ user.wechatId }}</td>
          <td>
            <input type="checkbox" v-model="user.isWhitelisted" @change="updateWhitelist(user)" />
          </td>
          <td>
            <button @click="removeUser(user.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const users = ref([]);

onMounted(async () => {
  try {
    const res = await axios.get('/api/users');
    users.value = res.data;
  } catch (err) {
    console.error('获取用户列表失败:', err);
  }
});

const updateWhitelist = async (user) => {
  try {
    await axios.put(`/api/users/${user.id}`, user);
  } catch (err) {
    alert('更新白名单失败');
    // Revert UI change on error
    user.isWhitelisted = !user.isWhitelisted;
  }
};

const removeUser = async (id) => {
  if (confirm('确定要删除该用户吗？')) {
    try {
      await axios.delete(`/api/users/${id}`);
      users.value = users.value.filter(u => u.id !== id);
    } catch (err) {
      alert('删除用户失败');
    }
  }
};
</script>

<style scoped>
.whitelist-container {
  padding: 20px;
}
.user-table {
  width: 100%;
  border-collapse: collapse;
}
.user-table th, .user-table td {
  border: 1px solid #ddd;
  padding: 8px;
}
.user-table tr:nth-child(even) {
  background-color: #f2f2f2;
}
.user-table tr:hover {
  background-color: #ddd;
}
</style>